<?php
namespace app\admin\controller;
header("Access-Control-Allow-Origin: http://www.importndsf.com");
header("content-type:text/html;charset=utf-8");
use think\Controller;
use think\Cache;
require_once(dirname(__FILE__) . '/' . "../extend/wxpay/lib/WxPay.Api.php");
require_once(dirname(__FILE__) . '/' . "../extend/wxpay/lib/WxPay.Config.php");
require_once(dirname(__FILE__) . '/' . "../extend/wxpay/lib/WxPay.Data.php");
require_once(dirname(__FILE__) . '/' . "../extend/wxpay/lib/WxPay.Exception.php");
require_once (dirname(__FILE__).'/'."../../common/function.php");

class Wxgzhpay extends Controller{

    public function xcxpay(){
        $openid=$this->GetOpenid();
        //dump($openid);die;
        $user_info['access_token']=$openid['access_token'];
        $user_info['openid']=$openid['openid'];
        $user_info['lang']='zh_CN';
        $url='https://api.weixin.qq.com/sns/userinfo';
        $arr=$this->get($url,$user_info);
        $data=json_decode($arr,true);
        Cache::set('userinfo',$data);
        $cache=Cache::get('userinfo');
        return $cache;
        //dump($cache);die;
        $this->assign('userinfo',$cache);
        return $this->fetch('Wxgzhpay/xcxpay');
    }

    /**
     *封装get请求
     *params $url
     *author leesin.
     *date 2018/3/8
     */
    public function getContents($url){
        /*//初始化链接
        $ch = curl_init($url);
        //设置选项
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,false);
        //执行请求
        $response = curl_exec($ch);
        //关闭链接
        curl_close($ch);*/
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        //curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

        $tmpInfo = curl_exec($curl);     //返回api的json对象
        //关闭URL请求
        curl_close($curl);
        //返回结果
        return $tmpInfo;
    }

    /**
     *拼接get请求
     *params url params
     *author leesin.
     *date 2018/3/8
     */
    public function get($baseUrl,$paramsArr){
        //拼接请求的url地址
        $url = $this->combineUrl($baseUrl,$paramsArr);
        //发送get请求
        return $this->getContents($url);
    }

    /**
     *拼接url地址
     *params url params
     *author leesin.
     *date 2018/3/8
     */
    public function combineUrl($baseUrl,$paramsArr){
        $url = $baseUrl;
        $json = '?';
        foreach ($paramsArr as $name=>$val){
            $url.=$json.$name.'='.$val;
            $json = '&';
        }
        return $url;
    }
    /**
     *
     * 通过跳转获取用户的openid，跳转流程如下：
     * 1、设置自己需要调回的url及其其他参数，跳转到微信服务器https://open.weixin.qq.com/connect/oauth2/authorize
     * 2、微信服务处理完成之后会跳转回用户redirect_uri地址，此时会带上一些参数，如：code
     *
     * @return 用户的openid
     */
    public function GetOpenid()
    {
        //通过code获得openid
        if (!isset($_GET['code'])){
            //触发微信返回code码
            $baseUrl = urlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].$_SERVER['QUERY_STRING']);
            $url = $this->__CreateOauthUrlForCode($baseUrl);
            //return $url;
            //return "<script>window.location='".$url."'</script>";
            Header("Location: $url");
            exit();
        } else {
            //获取code码，以获取openid
            $code = $_GET['code'];
            $openid = $this->getOpenidFromMp($code);
            return $openid;
        }
    }

    /**
     *
     * 构造获取open和access_toke的url地址
     * @param string $code，微信跳转带回的code
     *
     * @return 请求的url
     */
    private function __CreateOauthUrlForOpenid($code)
    {
        $urlObj["appid"] = \WxPayConfig::APPID;
        $urlObj["secret"] = \WxPayConfig::APPSECRET;
        $urlObj["code"] = $code;
        $urlObj["grant_type"] = "authorization_code";
        $bizString = $this->ToUrlParams($urlObj);
        return "https://api.weixin.qq.com/sns/oauth2/access_token?".$bizString;
    }
    /**
     *
     * 构造获取code的url连接
     * @param string $redirectUrl 微信服务器回跳的url，需要url编码
     *
     * @return 返回构造好的url
     */
    private function __CreateOauthUrlForCode($redirectUrl)
    {
        $urlObj["appid"] = \WxPayConfig::APPID;
        $urlObj["redirect_uri"] = "$redirectUrl";
        $urlObj["response_type"] = "code";
        $urlObj["scope"] = "snsapi_userinfo";
        $urlObj["state"] = "STATE"."#wechat_redirect";
        $bizString = $this->ToUrlParams($urlObj);
        return "https://open.weixin.qq.com/connect/oauth2/authorize?".$bizString;
    }

    /**
     *
     * 通过code从工作平台获取openid机器access_token
     * @param string $code 微信跳转回来带上的code
     *
     * @return openid
     */
    public function GetOpenidFromMp($code)
    {
        $url = $this->__CreateOauthUrlForOpenid($code);
        //初始化curl
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        if(\WxPayConfig::CURL_PROXY_HOST != "0.0.0.0"
            && \WxPayConfig::CURL_PROXY_PORT != 0){
            curl_setopt($ch,CURLOPT_PROXY, \WxPayConfig::CURL_PROXY_HOST);
            curl_setopt($ch,CURLOPT_PROXYPORT, \WxPayConfig::CURL_PROXY_PORT);
        }
        //运行curl，结果以jason形式返回
        $res = curl_exec($ch);
        curl_close($ch);
        //取出openid
        $data = json_decode($res,true);
        $this->data = $data;
        $openid = $data['openid'];
        return $data;
    }

    /**
     *
     * 拼接签名字符串
     * @param array $urlObj
     *
     * @return 返回已经拼接好的字符串
     */
    private function ToUrlParams($urlObj)
    {
        $buff = "";
        foreach ($urlObj as $k => $v)
        {
            if($k != "sign"){
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }

    /**
     * @return string
     * 下单的回调函数
     * @author  曹旺
     * @data  15:51
     */
    /*public function notify()
    {
        //echo 123;die;
        $data = file_get_contents('php://input');
        //文件日志
        Pay::fileLog(123, 'notifyss.log');
        //自定义参数
        //$data = 'params=eyJ1aWQiOjYsIm9yZGVyTnVtYmVyIjoiVzAzMjMwOTE2NDU2MDA5MSIsIm1ldGhvZCI6ImFsaXBheSJ9&gmt_create=2018-03-23+09%3A23%3A55&charset=UTF-8&gmt_payment=2018-03-23+09%3A23%3A59&notify_time=2018-03-23+09%3A23%3A59&subject=%E4%B8%AD%E5%BD%A7%E7%89%8C%E7%85%A7%E8%AE%A2%E5%8D%95&sign=ViRJXK80%2FtaStPno0BbhIWIceWBrQulFxbWbkvPpa4D%2FqYNLifmw3nANMB%2FdLBeFWO1ojfXClw5tXXXD3M%2Ff1ZqC5UOu2BBK%2BdSfsFphE%2BnhlBpyuLWhmwe80Cz%2FgppONIjI8PsQO4q0EgJ9Qvsd7qICAjiR5YqIcoa3DZjL4rzwkDxxq8UebTPF78KOmVvLz2bvzzV6%2BE5YuJA8No5Lo5eYgunISu0kafuvOaEMBlzE8%2FKsVIVxVCuq55GbBefu7tz1YvEWtHUtuBtHBHcDzJiyN4xXd7hR9OhhYIivz%2FvS8HUhLQSD%2BgGdQ8Kk%2FHRYzNEJIPjPHacG5BwO8QcVdw%3D%3D&buyer_id=2088112217380294&body=%E4%B8%AD%E5%BD%A7%E7%89%8C%E7%85%A7%E8%AE%A2%E5%8D%95&invoice_amount=0.01&version=1.0&notify_id=59e2c9cfaab8e656673bb68821caf3ei8p&fund_bill_list=%5B%7B%22amount%22%3A%220.01%22%2C%22fundChannel%22%3A%22ALIPAYACCOUNT%22%7D%5D&notify_type=trade_status_sync&out_trade_no=W032309164560091&total_amount=0.01&trade_status=TRADE_SUCCESS&trade_no=2018032321001004290559506068&auth_app_id=2018032202425729&receipt_amount=0.01&point_amount=0.00&app_id=2018032202425729&buyer_pay_amount=0.01&sign_type=RSA2&seller_id=2088921759977422';
        $params = $this->decodeParams($this->getNotifyParams($data));
        Pay::fileLog(123456, 'paramsss.log');
        //处理订单（与h5一样调用h5处理订单的方法）
        $H5Model = new H5pay();
        //$key = '9JTOvroPhcxaAnosVXkwGtWlilsCkkOR';
        $result = $H5Model->notify($data, $params);
        return $result;

    }*/
    /**
     * 解码自定义参数
     * author caowang.
     * date 2018/3/22
     */
    public static function decodeParams($params){
        return json_decode(base64_decode($params), true);
    }
    /**
     * @param $data微信传的参数（下单时自定义的参数）
     * @return \SimpleXMLElement[]|string
     * 获取通知数据
     * @author  曹旺
     * @data  15:52
     */
    public function getNotifyParams($data){
        $xml_parser = xml_parser_create();
        if(!xml_parse($xml_parser,$data,true)){
            //支付宝数据
            parse_str($data, $data);
            $params = urldecode($data['params']);
        }else {
            //微信数据
            $obj = simplexml_load_string($data);
            $params = $obj->attach;

        }
        return $params;
    }
}

?>
  